<template>
    <div class="user-management">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>用户管理</span>
                    <el-button type="primary" @click="showAddDialog = true">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        添加用户
                    </el-button>
                </div>
            </template>

            <!-- 搜索区域 -->
            <div class="search-area">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-input v-model="searchForm.search" placeholder="搜索用户名或邮箱" @keyup.enter="handleSearch"
                            clearable>
                            <template #append>
                                <el-button @click="handleSearch">
                                    <el-icon>
                                        <Search />
                                    </el-icon>
                                </el-button>
                            </template>
                        </el-input>
                    </el-col>
                    <el-col :span="4">
                        <el-button @click="resetSearch">重置</el-button>
                    </el-col>
                </el-row>
            </div>

            <!-- 用户表格 -->
            <CommonTable :loading="loading" :data="users" :offset="280" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="id" label="ID" width="80" sortable />
                <el-table-column prop="username" label="用户名" sortable />
                <el-table-column prop="email" label="邮箱" sortable />
                <el-table-column prop="role" label="角色" sortable>
                    <template #default="{ row }">
                        <el-tag v-if="row.role" type="primary">{{ row.role }}</el-tag>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column prop="is_active" label="状态" sortable>
                    <template #default="{ row }">
                        <el-tag :type="row.is_active ? 'success' : 'danger'">
                            {{ row.is_active ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="created_at" label="创建时间" sortable />
                <el-table-column label="操作" width="180" fixed="right">
                    <template #default="{ row }">
                        <el-button size="small" @click="editUser(row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteUser(row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </CommonTable>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.per_page"
                    :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 添加/编辑用户对话框 -->
        <el-dialog v-model="showAddDialog" :title="editingUser ? '编辑用户' : '添加用户'" width="500px" @closed="resetForm">
            <el-form ref="userFormRef" :model="userForm" :rules="userRules" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" />
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email" type="email" />
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="userForm.password" type="password"
                        :placeholder="editingUser ? '留空表示不修改密码' : '请输入密码'" show-password />
                </el-form-item>

                <el-form-item label="角色" prop="role_id">
                    <el-select v-model="userForm.role_id" placeholder="请选择角色" clearable>
                        <el-option v-for="role in roles" :key="role.id" :label="role.name" :value="role.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="状态" prop="is_active">
                    <el-switch v-model="userForm.is_active" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showAddDialog = false">取消</el-button>
                    <el-button type="primary" :loading="submitLoading" @click="submitUser">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import CommonTable from '@/components/CommonTable.vue'

const loading = ref(false)
const submitLoading = ref(false)
const showAddDialog = ref(false)
const editingUser = ref(null)
const selectedUsers = ref([])

const users = ref([])
const roles = ref([])

const searchForm = reactive({
    search: ''
})

const pagination = reactive({
    page: 1,
    per_page: 10,
    total: 0,
    pages: 0
})

const userForm = reactive({
    username: '',
    email: '',
    password: '',
    role_id: null,
    is_active: true
})

const userFormRef = ref()

const userRules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    password: [
        {
            validator: (rule, value, callback) => {
                if (!editingUser.value && !value) {
                    callback(new Error('请输入密码'))
                } else if (value && value.length < 6) {
                    callback(new Error('密码长度不能少于6位'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}

// 获取用户列表
const fetchUsers = async () => {
    loading.value = true
    try {
        const params = {
            page: pagination.page,
            per_page: pagination.per_page,
            search: searchForm.search
        }

        const response = await axios.get('/api/users', { params })
        users.value = response.data.users
        pagination.total = response.data.total
        pagination.pages = response.data.pages
    } catch (error) {
        ElMessage.error('获取用户列表失败: ' + (error.response?.data?.message || error.message))
    } finally {
        loading.value = false
    }
}

// 获取角色列表
const fetchRoles = async () => {
    try {
        const response = await axios.get('/api/roles/all')
        roles.value = response.data.roles
    } catch (error) {
        ElMessage.error('获取角色列表失败: ' + (error.response?.data?.message || error.message))
    }
}

// 搜索
const handleSearch = () => {
    pagination.page = 1
    fetchUsers()
}

// 重置搜索
const resetSearch = () => {
    searchForm.search = ''
    pagination.page = 1
    fetchUsers()
}

// 分页
const handleSizeChange = (val) => {
    pagination.per_page = val
    pagination.page = 1
    fetchUsers()
}

const handleCurrentChange = (val) => {
    pagination.page = val
    fetchUsers()
}

// 选择变化
const handleSelectionChange = (val) => {
    selectedUsers.value = val
}

// 编辑用户
const editUser = (user) => {
    editingUser.value = user
    userForm.username = user.username
    userForm.email = user.email
    userForm.password = ''
    userForm.role_id = user.role_id
    userForm.is_active = user.is_active
    showAddDialog.value = true
}

// 删除用户
const deleteUser = async (user) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除用户 "${user.username}" 吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        await axios.delete(`/api/users/${user.id}`)
        ElMessage.success('删除成功')
        fetchUsers()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
        }
    }
}

// 提交用户表单
const submitUser = async () => {
    if (!userFormRef.value) return

    await userFormRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                const data = { ...userForm }
                if (editingUser.value && !data.password) {
                    delete data.password
                }

                if (editingUser.value) {
                    await axios.put(`/api/users/${editingUser.value.id}`, data)
                    ElMessage.success('更新成功')
                } else {
                    await axios.post('/api/users', data)
                    ElMessage.success('创建成功')
                }

                showAddDialog.value = false
                fetchUsers()
            } catch (error) {
                ElMessage.error((editingUser.value ? '更新' : '创建') + '失败: ' + (error.response?.data?.message || error.message))
            } finally {
                submitLoading.value = false
            }
        }
    })
}

// 重置表单
const resetForm = () => {
    editingUser.value = null
    userForm.username = ''
    userForm.email = ''
    userForm.password = ''
    userForm.role_id = null
    userForm.is_active = true
    userFormRef.value?.resetFields()
}

onMounted(() => {
    fetchUsers()
    fetchRoles()
})
</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-area {
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}
</style>
